#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import pymysql
import traceback
from pymysql.err import MySQLError


def now():
    """返回当前时间"""
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


def query_mysql_db(db_config: dict, table, condition):
    """数据库查询，返回tuple"""
    try:
        cursor = pymysql.connect(
            host=db_config['host'], port=db_config['port'], user=db_config['username'],
            password=db_config['password'], database=db_config['database'], connect_timeout=5
        ).cursor()
    except MySQLError:
        print(f"{db_config['env']}环境，数据库连接的异常：{traceback.format_exc()}")
    else:
        try:
            cursor.execute(f"select * from {table} where {condition}")
            one_data = cursor.fetchone()
        except MySQLError:
            traceback.print_exc()
            print(f"{db_config['env']}环境，数据库查询语句的异常：{traceback.format_exc()}")
        else:
            if one_data:
                print(f"{now()} - 数据查询{db_config['env']}环境 - select * from {table} where {condition} - Y")
            else:
                print(f"{now()} - 数据查询{db_config['env']}环境 - select * from {table} where {condition} - {one_data}")
            return one_data
        # finally:
        #     cursor.close()

